import java.util.ArrayList;
import java.util.List;

/**
 * 1863. 找出所有子集的异或总和再求和
 * https://leetcode-cn.com/problems/sum-of-all-subset-xor-totals/
 */
public class Solutions_1863 {
    public static void main(String[] args) {
        int[] nums1 = {1, 3};  // output: 6
        int[] nums2 = {5, 1, 6};  // output: 28
        int[] nums3 = {3, 4, 5, 6, 7, 8};  // output: 480

        List<int[]> inputs = new ArrayList<>();
        inputs.add(nums1);
        inputs.add(nums2);
        inputs.add(nums3);

        for (int[] input : inputs) {
            int result = subsetXORSum(input);
            System.out.println(result);
        }
    }

    // 1. DFS 找出 nums 的所有的子集
    // 2. 对所有的子集进行异或运算
    public static int subsetXORSum(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        List<Integer> list = new ArrayList<>();

        if (nums.length == 1) {
            return nums[0];
        }
        dfs(nums, 0, lists, list);
        int res = 0;
        for (List<Integer> curList : lists) {
            int xor = 0;
            for (int num : curList) {
                xor ^= num;
            }
            res += xor;
        }
        return res;
    }

    public static void dfs(int[] nums, int idx, List<List<Integer>> lists,
                           List<Integer> list) {
        for (int i = idx; i < nums.length; i++) {
            list.add(nums[i]);
            lists.add(new ArrayList<>(list));
            dfs(nums, i + 1, lists, list);
            list.remove(list.size() - 1);
        }
    }
}
